package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-04
 * Time: 16:27
 */
class MyBlockingQueue {
    private int[] items = new int[1000];
    //[head, tail)为有效元素
    volatile private int head;
    volatile private int tail;
    volatile private int size;

    //入队列
    synchronized public void put(int elem) throws InterruptedException {
        while (size == items.length) {//不使用if，防止被其他线程的interrupted唤醒，此时还没有满足条件
            this.wait();//队列满，阻塞
        }
        items[tail] = elem;
        tail++;
        //tail到队尾需要从头再来
        if (tail == items.length) {//该写法更快
            tail = 0;
        }
        //tail %= items.length;
        size++;
        this.notify();//唤醒take
    }

    //出队列
    synchronized public Integer take() throws InterruptedException {
        while (size == 0) {
            this.wait();//空队列，阻塞
        }
        int value = items[head];
        head++;
        if (head == items.length) {
            head = 0;
        }
        size--;
        this.notify();//唤醒put
        return value;
    }
}


public class ThreadDemo21 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费元素：" + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //生产者
        Thread t2 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    System.out.println("生产元素：" + value);
                    queue.put(value);
                    value++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}
